﻿/**************************************************************************
创建时间:	2019/5/14
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述：
记	录：
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ASmile.Win
{
    public static class ControlEx
    {
        /// <summary>
        /// 递归查找指定控件的子控件
        /// </summary>
        /// <param name="ctr">要查找的父级控件</param>
        /// <param name="FindAfter">找到后的处理方法,返回true则跳出查找</param>
        /// <param name="FindMatch">查找控件的匹配方法,返回true表示当前控件</param>
        public static void FindControl(this Control ctr, Func<Control, bool> FindAfter, Func<Control, bool> FindMatch)
        {
            foreach (Control itemCtr in ctr.Controls)
            {
                if (FindMatch(itemCtr))
                {
                    if (FindAfter(itemCtr)) return;
                }
                else
                {
                    FindControl(itemCtr, FindAfter, FindMatch);
                }
            }
        }

        /// <summary>
        /// 递归查找指定控件工具栏
        /// </summary>
        /// <param name="ctr"></param>
        /// <param name="FindAfter"></param>
        public static void FindToolStrip(this Control ctr, Func<Control, bool> FindAfter)
        {
            FindControl(ctr, FindAfter, FindMatch);

            bool FindMatch(Control c)
            {
                if (c is ToolStrip toolBar)
                {
                    FindAfter(toolBar);
                }
                return false;
            }

        }
        /// <summary>
        /// 使用Control的Invoke执行方法
        /// </summary>
        public static void InvokeTask(this Control ctr, Action Act)
        {
            ctr.Invoke(Act);
        }
        /// <summary>
        /// 使用Control的Invoke执行方法,带有参数
        /// </summary>
        public static void InvokeTask(this Control ctr, Action<object> Act, object state)
        {
            ctr.Invoke(Act, state);
        }

        public static void InvokeTaskAsyn(this Control ctr, Action Act)
        {
            Action act = () => ctr.InvokeTask(Act);
            Task.Factory.StartNew(act);
        }

        public static void InvokeTaskAsyn(this Control ctr, Action<object> Act, object state)
        {
            Action<object> act = (o) => ctr.InvokeTask(Act, o);
            Task.Factory.StartNew(act, state);
        }
    }
}